//
//  BVNextOrderViewController.m
//  BuyVegetables1
//
//  Created by 叶思超 on 15/11/4.
//  Copyright (c) 2015年 叶思超. All rights reserved.
//

#import "BVNextOrderViewController.h"

#import "BVCorrectOrderViewController.h"
#import "BVConst.h"
#import "NSString+Extension.h"
#import "UIView+Extension.h"
#import "BVAddOrderRemarksViewController.h"
#import "BVRecevicedAddressViewController.h"
#import "BVMyOrderViewController.h"
#import "BVDiscountViewController.h"
#import "BVReceviceAddress.h"
#import "HttpTool.h"
#import "BVShopCart.h"
#import "BVShopsLeftCategoryDetail.h"
#import "BVDurationTime.h"
#import "BVTime.h"
#import "MJExtension.h"
#import "BVTimeCell.h"
#import "MBProgressHUD+MJ.h"
#import "BVMyDiscount.h"
#import "BVMyOrder.h"
#import "BVNextOrderShopDetail.h"
#import "BVNextOrder.h"
#import "MJExtension.h"
#import "BVMyOrderViewController.h"
@interface BVNextOrderViewController () <UIActionSheetDelegate, BVRecevicedAddressViewControllerDelegate, UITableViewDataSource, UITableViewDelegate, BVAddOrderRemarksViewControllerDelegated, BVDiscountViewControllerDelegate>
/**
 *  底部父视图scrollView
 */
@property (nonatomic, strong) UIScrollView *scrollView;
/**
 *  地址父视图addressView
 */
@property (nonatomic, strong) UIView *addressView;
/**
 *  支付方式父视图payView
 */
@property (nonatomic, strong) UIView *payView;
/**
 *  在线支付按钮
 */
@property (nonatomic, weak) UIButton *onlineSelectedButton;
/**
 *  当面付款
 */
@property (nonatomic, weak) UIButton *currentSelectedButton;
/**
 *  送达时间和备注父视图timeAndRemaksView
 */
@property (nonatomic, strong) UIView *timeAndRemaksView;
/**
 *  送达时间
 */
@property (nonatomic, strong) UILabel *getSendLabel;
/**
 *  抵价券
 */
@property (nonatomic, strong) UIView *disCountView;
/**
 *  商品总价格
 */
@property (nonatomic, strong) UILabel *priceLabel;
/**
 *  商品基本信息
 */
@property (nonatomic, strong) UIView *shopInfo;
/**
 *  存放所有时间信息
 */
@property (nonatomic, strong) NSMutableArray *times;
/**
 *  添加tableView
 */
@property (nonatomic, strong) UITableView *tableView;
/**
 *  蒙板
 */
@property (nonatomic, weak) UIButton *coverButton;
/**
 *  添加批注
 */
@property (nonatomic, weak) UILabel *remindLabel;
/**
 *  保存收货地址
 */
@property (nonatomic, strong) BVReceviceAddress *receviceAddress;
/**
 *  抵价券
 */
@property (nonatomic, weak) UILabel *getDiscountLabel;
/**
 *  保存抵金券
 */
@property (nonatomic, strong) BVMyDiscount *myDiscount;
/**
 *  存放选中送货日期
 */
@property (nonatomic, strong) BVTime *myTime;
/**
 *  抵价券金额
 */
@property (nonatomic, strong) UILabel *discountPriceLabel;
/**
 *  存放再来一单商品数据
 */
@property (nonatomic, strong) NSMutableArray *nextOrder;

/**
 * 支付订单号
 */
@property (nonatomic,strong) NSString * orderNum;

//邮费
@property (nonatomic,weak) UILabel * distributeLabel;

//抵价券   邮费
@property (nonatomic,strong) UIView * discountAndDistributeView;

//总价
@property (nonatomic,assign) CGFloat allPrice;

/**
 *  对比再来一单商品数据
 */
@property (nonatomic, strong) NSMutableArray *nextOrderIs;
/**
 *  对比再来一单商品价格   盛放点击确认下单时获得的价格数据
 */
@property (nonatomic, strong) NSMutableArray * arryIs;
/**
 *  对比再来一单商品价格   以前的数据
 */
@property (nonatomic, strong) NSMutableArray * arryOld;


@end

@implementation BVNextOrderViewController

- (NSMutableArray *)nextOrder {
    if (!_nextOrder) {
        _nextOrder = [NSMutableArray array];
    }
    return _nextOrder;
}

- (NSMutableArray *)nextOrderIs {
    if (!_nextOrderIs) {
        _nextOrderIs = [NSMutableArray array];
    }
    return _nextOrderIs;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        CGFloat tableViewW = BVScreenW - 2 * 20;
        CGFloat tableViewH = 300;
        CGFloat tableViewX = 20;
        CGFloat tableViewY = (BVScreenH - tableViewH) * 0.5;
        _tableView.frame = CGRectMake(tableViewX, tableViewY, tableViewW, tableViewH);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (NSMutableArray *)times {
    if (!_times) {
        _times = [NSMutableArray array];
    }
    return _times;
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.frame = CGRectMake(0, 64, BVScreenW, BVScreenH - 64);
        _scrollView.backgroundColor = [UIColor clearColor];
        _scrollView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_scrollView];
    }
    return _scrollView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置导航栏
    [self setupNav];
    
    // 获取送达时间
    [self loadSendShopsTime];
    
    // 获取下一单数据
    [self loadNextShopData];
}

#pragma mark -- 获取下一单
- (void)loadNextShopData {
    // 拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetablePayAPI/doComeAgainOrderById", Path];
    
    // 拼接参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"order_id"] = self.myOrder.order_id;
    
    [HttpTool get:url params:params success:^(id responseObj) {
        if ([responseObj[@"code"] isEqualToString:@"1"]) {
             BVLog(@"()()()()()()   %@",responseObj);
            BVNextOrder *nextOrder = [BVNextOrder objectWithKeyValues:responseObj[@"data"]];
            
            [self.nextOrder addObject:nextOrder];
            // 设置UI
            [self setupUI];
            
            // 去支付
            [self setupBottomShopCart];
        }else{
            [MBProgressHUD showError:@"数据获取失败"];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showError:@"网络错误"];
    }];
}

#pragma mark -- 获取送货时间
- (void)loadSendShopsTime {
    
    // 拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetablePayAPI/getDurationList", Path];
    
    [HttpTool get:url params:nil success:^(id responseObj) {
        if ([responseObj[@"code"] isEqualToString:@"1"]) {

            NSArray *array = [BVTime objectArrayWithKeyValuesArray:responseObj[@"data"]];
            BVLog(@"这是送货时间的数组-----%@",array);
            
            [self.times addObjectsFromArray:array];
        } else {
            [MBProgressHUD showError:@"获取送货时间失败"];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showError:@"网络错误"];
    }];
}

- (void)setupBottomShopCart {
    // 左侧购物车父视图
    UIView *leftShopCart = [[UIView alloc] init];
    leftShopCart.frame = CGRectMake(0, BVScreenH - 40,  BVScreenW, 40);
    leftShopCart.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:leftShopCart];
    
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(0, 0, BVScreenW, 0.5);
    label.backgroundColor = BVBackgroundLightGrayColor;
    [leftShopCart addSubview:label];

    
    CGFloat goodsMoney = [self getGoodMoney];
    CGFloat distributeMoney = [self getDistributeMoeny:goodsMoney];
    
    self.distributeLabel.text = @"免运费";
    //self.distributeLabel.text = [NSString stringWithFormat:@"￥%.2f",distributeMoney];
    self.allPrice = goodsMoney + distributeMoney;
    
    // 总价格
    self.priceLabel = [[UILabel alloc] init];
    self.priceLabel.textColor = BVBaseTextBlackColor;
    self.priceLabel.frame = CGRectMake(10, 0, BVScreenW * 0.7 - 10, 40);
    self.priceLabel.text = [NSString stringWithFormat:@"总计:%.2f", self.allPrice];
    [leftShopCart addSubview:self.priceLabel];
    
    // 右侧结算按钮
    UIButton *balanceButton = [[UIButton alloc] init];
    balanceButton.frame = CGRectMake(BVScreenW * 0.7, 0, BVScreenW * 0.3, leftShopCart.height);
    [balanceButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [balanceButton setTitle:@"确认下单" forState:UIControlStateNormal];
    balanceButton.titleLabel.font = [UIFont systemFontOfSize:15];
    balanceButton.backgroundColor = BVBaseOrangeColor;
    [balanceButton addTarget:self action:@selector(lookIs) forControlEvents:UIControlEventTouchUpInside];
    [leftShopCart addSubview:balanceButton];
}
#pragma mark -- 确认下单之前对比价格
-(void)lookIs{
    
    BVLog(@"这是正在下单按钮的点击");
    
    [self.nextOrderIs removeAllObjects];
    
    // 拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetablePayAPI/doComeAgainOrderById", Path];
    // 拼接参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"order_id"] = self.myOrder.order_id;
    
    [HttpTool get:url params:params success:^(id responseObj) {
        if ([responseObj[@"code"] isEqualToString:@"1"]) {
            
            BVNextOrder *nextOrder = [BVNextOrder objectWithKeyValues:responseObj[@"data"]];
            [self.nextOrderIs addObject:nextOrder];
            
            //用来对比的
            BVNextOrder *nextOrder2 = self.nextOrderIs[0];
            NSArray *shopsArray2 = nextOrder2.order_assort;
            NSInteger shopsCount = shopsArray2.count;
            
            //以前的
            BVNextOrder *nextOrder3 = self.nextOrder[0];
            NSArray *shopsArray3 = nextOrder3.order_assort;
            
            
            //初始化数组
            self.arryIs = [[NSMutableArray alloc]init];
            self.arryOld = [[NSMutableArray alloc]init];
            //遍历两个数组，将价格装到新的数组内
            for (NSInteger i = 0; i < shopsCount; i++) {
                
             BVNextOrderShopDetail *shopDetail2 = shopsArray2[i];
                [self.arryIs addObject:shopDetail2.sum_money];
            
            BVNextOrderShopDetail *shopDetail3 = shopsArray3[i];
                [self.arryOld addObject:shopDetail3.sum_money];
                
            }
            
            //比较两个数组的内容是否相同
            bool bol = false;
            if (self.arryIs.count == self.arryOld.count) {
                bol = true;
                for (int16_t i = 0; i < shopsCount; i++) {
                    if (![[self.arryIs objectAtIndex:i] isEqualToString:[self.arryOld objectAtIndex:i]]) {
                        bol = false;
                        break;
                    }  
                }
                if (bol) {
                    BVLog(@"两个数组内容相同");
                    //如果两个数组的内容相同，那么就去调用下一个方法
                    [self confirmOrderClick];
                }
                else{
                    //数组内的价格有不一样的 弹出提示
                    [MBProgressHUD showError:@"商品有变动  请重新选择"];
                    BVLog(@"两个数组内容--不相同");
                }
                
            }else{
                    //数组内的数量不同  弹出提示
                [MBProgressHUD showError:@"商品有变动  请重新选择"];
                BVLog(@"两个数组元素数量不相等");
            }
            
            
        }else{
            [MBProgressHUD showError:@"数据获取失败"];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showError:@"网络错误"];
    }];

}

#pragma mark -- 确认下单
- (void)confirmOrderClick {
    
    // 拼接参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dict = [defaults objectForKey:@"USERINFO"];
    NSString *user_id = dict[@"id"];
    
    if (user_id != nil) {
        BVNextOrder *nextOrder = self.nextOrder[0];
        params[@"user_id"] = user_id;
        params[@"receiver"] = ((BVNextOrder *)self.nextOrder.firstObject).receiver;
        params[@"mobile"] = nextOrder.mobile;
        BVLog(@"手机格式 ---%@",nextOrder.mobile);
        // 订单信息
        BVLog(@"%@",dict[@"username"]);
        NSString *order_info = @"";
        //BVNextOrder *nextOrder = self.nextOrder[0];
        NSArray *shopsArray = nextOrder.order_assort;
        NSInteger shopCount = shopsArray.count;
        for (NSInteger i = 0; i < shopCount; i++) {
            BVNextOrderShopDetail *shopDetail = shopsArray[i];
            
            order_info = [NSString stringWithFormat:@"%@%@_%@_%@",order_info, shopDetail.goods_id, shopDetail.number, shopDetail.sum_money];
            
            if (i < shopCount - 1) {
                order_info = [NSString stringWithFormat:@"%@,", order_info];
            }
        }
        params[@"order_info"] = order_info;
        
        // 备注信息
        if ([self.remindLabel.text isEqualToString:@"点击添加备注"]) {
            params[@"beizhu"] = @"";
        } else {
            params[@"beizhu"] = self.remindLabel.text;
        }
        
        // 优惠券
        if (self.myDiscount.coupon_id == nil) {
            params[@"use_coupon_id"] = @"";
        } else {
            params[@"use_coupon_id"] = self.myDiscount.coupon_id;
        }
        
        // 总金额
        params[@"money"] = [[self.priceLabel.text componentsSeparatedByString:@":"] lastObject];
        
        if (self.receviceAddress == nil) { // 没有选择收货地址
            if (nextOrder.address == nil) {
                [MBProgressHUD showError:@"请选择地址" toView:self.view];
            } else {
                params[@"address"] = nextOrder.address;
            }
            
            if (self.onlineSelectedButton.selected) { // 在线支付
                params[@"pay_status"] = @"1";
            } else if (self.currentSelectedButton.selected) { // 货到付款
                params[@"pay_status"] = @"2";
            }
            
            // 送达时间
            if ([self.getSendLabel.text isEqualToString:@"请选择送达时间"]) {
                [MBProgressHUD showError:@"选择送达时间" toView:self.view];
            } else {
                params[@"reach_time"] = [NSString stringWithFormat:@"%@_%@",self.myTime.current_date, self.getSendLabel.text];
                
                //拼接请求地址
                NSString * city1 = nextOrder.city;
                NSString *city2;
                if ([city1 containsString:@"市"]) {
                    city2 = [city1 stringByReplacingOccurrencesOfString:@"市" withString:@""];
                }else{
                    city2 = city1;
                }
                NSString *dataUrl = [NSString stringWithFormat:@"%@/VegetablePayAPI/doVegetableUserOrderById?city=%@", Path,city2];
                NSString * url = [dataUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                
                [HttpTool get:url params:params success:^(id responseObj) {
                    BVLog(@"res-----%@",responseObj);
                    if ([responseObj[@"code"] isEqualToString:@"1"]) {
                        
                        self.orderNum = responseObj[@"data"][@"ordernum"];
                        
                        if (self.currentSelectedButton.isSelected) {
                            BVMyOrderViewController * myOrderVC = [BVMyOrderViewController new];
                            myOrderVC.isLeftMenu = YES;
                            ROOTNAVPUSH(myOrderVC, YES);
                            [BVShopCart deleteAllShopFromCart];
                        }else{
                            UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"支付宝", @"微信支付",nil];
                            [actionSheet showInView:self.scrollView];
                        }
                    } else {
                        [MBProgressHUD showError:@"下单失败"];
                    }
                } failure:^(NSError *error) {
                    [MBProgressHUD showError:@"网络错误"];
                }];
            }
        }
    } else {
        
    }

}
#pragma mark -- UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (!self.orderNum) return;

    if (buttonIndex == 0) {
        
        [self setupAlipay];
    }else if(buttonIndex == 1){
        
        [self setupWeiXinPay];
    }
}
#pragma mark-- 支付宝支付
- (void)setupAlipay {
    
    BVPayManager * mananer = [BVPayManager manager];
    
    [mananer pay:PayTypeAliPay orderNum:self.orderNum finishBlock:^{
        
        BVMyOrderViewController * myOrderVC = [BVMyOrderViewController new];
        myOrderVC.isLeftMenu = YES;
        ROOTNAVPUSH(myOrderVC, YES);
        [BVShopCart deleteAllShopFromCart];
        [[NSNotificationCenter defaultCenter] postNotificationName:PayFinishNotification object:nil userInfo:nil];
        BVLog(@"----------------支付完成----------------");
        
    } successBlock:^{
        
        BVLog(@"--------------------支付成功----------------------");
        
    } faileBlock:^{
        
        BVLog(@"--------------------支付失败----------------------");
        
    }];
}

#pragma mark -- 微信支付
- (void)setupWeiXinPay {
    
    BVPayManager * manager = [BVPayManager manager];
    [manager pay:PayTypeWX orderNum:self.orderNum finishBlock:^{
        
        BVMyOrderViewController * myOrderVC = [BVMyOrderViewController new];
        myOrderVC.isLeftMenu = YES;
        ROOTNAVPUSH(myOrderVC, YES);
        [BVShopCart deleteAllShopFromCart];
        [[NSNotificationCenter defaultCenter] postNotificationName:PayFinishNotification object:nil userInfo:nil];
        
        BVLog(@"------------------支付完成----------------");
    } successBlock:^{
        
        BVLog(@"--------------------支付成功----------------------");
        
    } faileBlock:^{
        
        BVLog(@"--------------------支付失败----------------------");
        
    }];
    
}

#pragma mark -- 设置UI
- (void)setupUI {
    // 地址设置
    [self setupAddress];
    
    // 支付方式
    [self setupPayMethods];
    
    // 设置送达时间和订单备注
    [self setupTimeAndRemaks];
    
    // 抵价券
    [self setupDiscountAndDistribute];
    
    // 商品基本信息
    [self setupShopInfo];
}

#pragma mark -- 设置商品基本信息
- (void)setupShopInfo {
    BVNextOrder *nextOrder = self.nextOrder[0];
    NSArray *shopsArray = nextOrder.order_assort;
    NSInteger shopsCount = shopsArray.count;
    self.shopInfo = [[UIView alloc] init];
    self.shopInfo.frame = CGRectMake(0, CGRectGetMaxY(self.discountAndDistributeView.frame) + 15, BVScreenW, 40 * shopsCount);
    self.shopInfo.backgroundColor = BVColor(233, 234, 235);
    [self.scrollView addSubview:self.shopInfo];
    
    for (NSInteger i = 0; i < shopsCount; i++) {
        BVNextOrderShopDetail *shopDetail = shopsArray[i];
        // 名称
        UILabel *nameLabel = [[UILabel alloc] init];
        nameLabel.x = 10;
        nameLabel.y = 40 * i;
        nameLabel.width = [NSString sizeWithText:shopDetail.title font:[UIFont systemFontOfSize:15]].width;
        nameLabel.height = 40;
        nameLabel.text = shopDetail.title;
        nameLabel.font = [UIFont systemFontOfSize:15];
        [self.shopInfo addSubview:nameLabel];
        
        // 价格
        UILabel *priceLabel = [[UILabel alloc] init];
        NSString *priceStr = [NSString stringWithFormat:@"¥%@", shopDetail.sum_money];
        priceLabel.font = [UIFont systemFontOfSize:14];
        priceLabel.y = nameLabel.y;
        priceLabel.width = 80;
        priceLabel.x = BVScreenW - priceLabel.width - 10;
        priceLabel.height = 40;
        priceLabel.text = priceStr;
        priceLabel.textAlignment = NSTextAlignmentRight;
        [self.shopInfo addSubview:priceLabel];
        
        // 商品的个数
        UILabel *shopCounts = [[UILabel alloc] init];
        NSString *poundsStr = [NSString stringWithFormat:@"共%@斤", shopDetail.sum_pounds];
        shopCounts.y = priceLabel.y;
        shopCounts.width = [NSString sizeWithText:[NSString stringWithFormat:@"x%@(%@)", shopDetail.number, poundsStr] font:[UIFont systemFontOfSize:13]].width;
        shopCounts.height = 40;
        shopCounts.x = priceLabel.x - shopCounts.width;
        shopCounts.font = [UIFont systemFontOfSize:13];
        shopCounts.text = [NSString stringWithFormat:@"x%@",shopDetail.number];
        [self.shopInfo addSubview:shopCounts];
        
        if (i < shopsCount - 1) {
            // 分割线
            UIView *separatorLine = [[UIView alloc] init];
            separatorLine.frame = CGRectMake(10, CGRectGetMaxY(nameLabel.frame), BVScreenW - 2 * 10, 0.8);
            separatorLine.backgroundColor = [UIColor blackColor];
            separatorLine.alpha = 0.15;
            [self.shopInfo addSubview:separatorLine];
        }

    }
    
    CGFloat maxHeight = CGRectGetMaxY(self.shopInfo.frame) + 15;
    BVLog(@"maxHeight == %f", maxHeight);
    if (maxHeight > BVScreenH - 40 - 64) {
        self.scrollView.contentSize = CGSizeMake(0, maxHeight + 60);
    }
}

/**
 *  抵价券
 */
- (void)setupDiscountAndDistribute {
    
    //抵价券和购物券父视图
    self.discountAndDistributeView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.timeAndRemaksView.frame) + 15, BVScreenW, 80)];
    self.discountAndDistributeView.backgroundColor = BVColor(233, 234, 235);
    [self.scrollView addSubview:self.discountAndDistributeView];
    
    //抵价券父视图
    UIView * discountView = [[UIView alloc] init];
    discountView.frame = CGRectMake(0, 0, BVScreenW, 39);
    discountView.backgroundColor = BVColor(233, 234, 235);
    [self.discountAndDistributeView addSubview:discountView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(discountClick)];
    [discountView addGestureRecognizer:tap];
    
    // 抵价券标签
    UILabel *discountLabel = [[UILabel alloc] init];
    discountLabel.frame = CGRectMake(10, 0, 60, 40);
    discountLabel.font = [UIFont systemFontOfSize:15];
    discountLabel.text = @"抵价券";
    [discountView addSubview:discountLabel];
    
    // 选择低价券
    UILabel *getDiscountLabel = [[UILabel alloc] init];
    getDiscountLabel.frame = CGRectMake(CGRectGetMaxX(discountLabel.frame) + 10, 0, BVScreenW - CGRectGetMaxX(discountLabel.frame) - 10 - 13 - 10 - 10, 40);
    getDiscountLabel.text = @"选择抵价券";
    getDiscountLabel.textAlignment = NSTextAlignmentRight;
    getDiscountLabel.font = [UIFont systemFontOfSize:13];
    [discountView addSubview:getDiscountLabel];
    self.getDiscountLabel = getDiscountLabel;
    
    UIImageView *discountImage = [[UIImageView alloc] init];
    discountImage.frame = CGRectMake(BVScreenW - 10 - 13, 10, 13, 20);
    discountImage.image = [UIImage imageNamed:@"qrdd_gray_go"];
    [discountView addSubview:discountImage];
    
    //横线
    UIView *separatorLine = [[UIView alloc] init];
    separatorLine.frame = CGRectMake(10, CGRectGetMaxY(discountLabel.frame), BVScreenW - 10 * 2, 0.8);
    separatorLine.backgroundColor = [UIColor blackColor];
    separatorLine.alpha = 0.15;
    [self.discountAndDistributeView addSubview:separatorLine];
    
    //运费
    // 运费父视图
    UIView * distributeView = [[UIView alloc] init];
    distributeView.frame = CGRectMake(0, CGRectGetMaxY(separatorLine.frame), BVScreenW, 39.6);
    [self.discountAndDistributeView addSubview:distributeView];
    
    // 添加运费标签
    UILabel *distributeLabel = [[UILabel alloc] init];
    distributeLabel.frame = CGRectMake(10, 0, 80, 39.6);
    distributeLabel.text = @"运费";
    distributeLabel.font = [UIFont systemFontOfSize:15];
    [distributeView addSubview:distributeLabel];
    
    
    // 添加钱label
    UILabel *moneyLabel = [[UILabel alloc] init];
    moneyLabel.frame = CGRectMake(BVScreenW - 80 - 10, 0, 80, 39.6);
    moneyLabel.font = [UIFont systemFontOfSize:13];
    moneyLabel.textAlignment = NSTextAlignmentRight;
    self.distributeLabel = moneyLabel;
    [distributeView addSubview:moneyLabel];
    
}

/**
 *  设置送达时间和订单备注
 */
- (void)setupTimeAndRemaks {
    self.timeAndRemaksView = [[UIView alloc] init];
    self.timeAndRemaksView.frame = CGRectMake(0, CGRectGetMaxY(self.payView.frame) + 15, BVScreenW, 80);
    self.timeAndRemaksView.backgroundColor = BVColor(233, 234, 235);
    [self.scrollView addSubview:self.timeAndRemaksView];
    
    // 送达时间父视图
    UIView *sendTimeView = [[UIView alloc] init];
    sendTimeView.frame = CGRectMake(0, 0, BVScreenW, 39.6);
    [self.timeAndRemaksView addSubview:sendTimeView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sendTimeSelected)];
    [sendTimeView addGestureRecognizer:tap];
    
    // 送达时间标签
    UILabel *sendTimeLabel = [[UILabel alloc] init];
    sendTimeLabel.frame = CGRectMake(10, 0, 80, 39.6);
    sendTimeLabel.font = [UIFont systemFontOfSize:15];
    sendTimeLabel.text = @"送达时间";
    [sendTimeView addSubview:sendTimeLabel];
    
    UIImageView *sendImage = [[UIImageView alloc] init];
    sendImage.frame = CGRectMake(BVScreenW - 10 - 13, 10, 13, 20);
    sendImage.image = [UIImage imageNamed:@"qrdd_gray_go"];
    [sendTimeView addSubview:sendImage];
    
    // 获取送达时间
    self.getSendLabel = [[UILabel alloc] init];
    self.getSendLabel.frame = CGRectMake(sendImage.x - 120 - 10, 0, 120, 39.6);
    self.getSendLabel.text = @"请选择送达时间";
    self.getSendLabel.textAlignment = NSTextAlignmentRight;
    self.getSendLabel.font = [UIFont systemFontOfSize:13];
    [sendTimeView addSubview:self.getSendLabel];
    
    // 分割线
    UIView *separatorLine = [[UIView alloc] init];
    separatorLine.frame = CGRectMake(10, CGRectGetMaxY(sendTimeView.frame), BVScreenW - 10 * 2, 0.8);
    separatorLine.backgroundColor = [UIColor blackColor];
    separatorLine.alpha = 0.15;
    [self.timeAndRemaksView addSubview:separatorLine];
    
    // 添加订单备注父视图
    UIView *addRemarksView = [[UIView alloc] init];
    addRemarksView.frame = CGRectMake(0, CGRectGetMaxY(separatorLine.frame), BVScreenW, 39.6);
    [self.timeAndRemaksView addSubview:addRemarksView];
    
    UITapGestureRecognizer *remarkTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addRemark)];
    [addRemarksView addGestureRecognizer:remarkTap];
    
    // 添加备注标签
    UILabel *addRemarksLabel = [[UILabel alloc] init];
    addRemarksLabel.frame = CGRectMake(10, 0, 80, 39.6);
    addRemarksLabel.text = @"订单备注";
    addRemarksLabel.font = [UIFont systemFontOfSize:15];
    [addRemarksView addSubview:addRemarksLabel];
    
    UIImageView *remarkImage = [[UIImageView alloc] init];
    remarkImage.frame = CGRectMake(BVScreenW - 10 - 13, 10, 13, 20);
    remarkImage.image = [UIImage imageNamed:@"qrdd_gray_go"];
    [addRemarksView addSubview:remarkImage];
    
    // 添加备注
    UILabel *remindLabel = [[UILabel alloc] init];
    remindLabel.frame = CGRectMake(90, 0, remarkImage.x - 80 - 20, 39.6);
    remindLabel.font = [UIFont systemFontOfSize:13];
    remindLabel.textAlignment = NSTextAlignmentRight;
    remindLabel.text = @"点击添加备注";
    [addRemarksView addSubview:remindLabel];
    self.remindLabel = remindLabel;
}

/**
 *  设置支付方式
 */
- (void)setupPayMethods {
    self.payView = [[UIView alloc] init];
    self.payView.frame = CGRectMake(0, CGRectGetMaxY(self.addressView.frame) + 15, BVScreenW, 80);
    self.payView.backgroundColor = BVColor(233, 234, 235);
    [self.scrollView addSubview:self.payView];
    
    // 在线支付标签
    UILabel *onlinePayLabel = [[UILabel alloc] init];
    onlinePayLabel.frame = CGRectMake(10, 0, 60, 39.6);
    onlinePayLabel.text = @"在线支付";
    onlinePayLabel.font = [UIFont systemFontOfSize:15];
    [self.payView addSubview:onlinePayLabel];
    
    // 选中按钮
    UIButton *onlineSelectedButton = [[UIButton alloc] init];
    onlineSelectedButton.frame = CGRectMake(BVScreenW - 10 - 40, 0, 40, 39.6);
//    onlineSelectedButton.selected = YES;
    [onlineSelectedButton setImage:[UIImage imageNamed:@"qrdd_nocheck"] forState:UIControlStateNormal];
    [onlineSelectedButton setImage:[UIImage imageNamed:@"qrdd_check"] forState:UIControlStateSelected];
    onlineSelectedButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [onlineSelectedButton addTarget:self action:@selector(onlineSelectedButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.payView addSubview:onlineSelectedButton];
    self.onlineSelectedButton = onlineSelectedButton;
    
    // 分割线
    UIView *separatorLine = [[UIView alloc] init];
    separatorLine.frame = CGRectMake(10, CGRectGetMaxY(onlinePayLabel.frame), BVScreenW - 10 * 2, 0.8);
    separatorLine.backgroundColor = [UIColor blackColor];
    separatorLine.alpha = 0.15;
    [self.payView addSubview:separatorLine];
    
    // 货到付款标签
    UILabel *currenttPayLabel = [[UILabel alloc] init];
    currenttPayLabel.frame = CGRectMake(10, CGRectGetMaxY(separatorLine.frame), 60, 39.6);
    currenttPayLabel.font = [UIFont systemFontOfSize:15];
    currenttPayLabel.text = @"货到付款";
    [self.payView addSubview:currenttPayLabel];
    
    // 选中按钮
    UIButton *currentSelectedButton = [[UIButton alloc] init];
    currentSelectedButton.frame = CGRectMake(BVScreenW - 10 - 40, CGRectGetMaxY(separatorLine.frame), 40, 39.6);
    [currentSelectedButton setImage:[UIImage imageNamed:@"qrdd_nocheck"] forState:UIControlStateNormal];
    [currentSelectedButton setImage:[UIImage imageNamed:@"qrdd_check"] forState:UIControlStateSelected];
    currentSelectedButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [currentSelectedButton addTarget:self action:@selector(currentSelectedButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.payView addSubview:currentSelectedButton];
    self.currentSelectedButton = currentSelectedButton;
    
    BVNextOrder *nextOrder = self.nextOrder[0];
    if ([nextOrder.pay_status isEqualToString:@"1"]) {
        self.onlineSelectedButton.selected = YES;
    } else {
        self.currentSelectedButton.selected = YES;
    }
}

/**
 *  设置地址
 */
- (void)setupAddress {
    BVNextOrder *nextOrder = self.nextOrder[0];
    
    self.addressView = [[UIView alloc] init];
    self.addressView.frame = CGRectMake(0, 0, BVScreenW, 60);
    self.addressView.backgroundColor = BVColor(233, 234, 235);
    [self.scrollView addSubview:self.addressView];
    
    // 地址标识
    UIImageView *addressImage = [[UIImageView alloc] init];
    addressImage.frame = CGRectMake(10, 20, 15, 20);
    addressImage.image = [UIImage imageNamed:@"qrdd_address"];
    [_addressView addSubview:addressImage];
    
    // 收获人姓名
    UILabel *receviceNameLabel = [[UILabel alloc] init];
    NSString *receviceName = nextOrder.receiver;
    CGFloat addressW = [NSString sizeWithText:receviceName font:[UIFont systemFontOfSize:15]].width;
    receviceNameLabel.frame = CGRectMake(CGRectGetMaxX(addressImage.frame) + 10, 10, addressW, 20);
    receviceNameLabel.font = [UIFont systemFontOfSize:15];
    receviceNameLabel.text = receviceName;
    [_addressView addSubview:receviceNameLabel];

    
    // 收货人联系方式
    UILabel *mobileLabel = [[UILabel alloc] init];
    NSString *mobileStr = nextOrder.mobile;
    CGFloat mobileW = [NSString sizeWithText:mobileStr font:[UIFont systemFontOfSize:15]].width;
    mobileLabel.frame = CGRectMake(CGRectGetMaxX(receviceNameLabel.frame) + 10, receviceNameLabel.y, mobileW, 20);
    mobileLabel.font = [UIFont systemFontOfSize:15];
    mobileLabel.text = mobileStr;
    [_addressView addSubview:mobileLabel];
    
    // 收货地址
    UILabel *addressLabel = [[UILabel alloc] init];
    addressLabel.frame = CGRectMake(receviceNameLabel.x, CGRectGetMaxY(receviceNameLabel.frame) + 5, BVScreenW - receviceNameLabel.x - 23, 20);
    addressLabel.font = [UIFont systemFontOfSize:14];
    addressLabel.text = nextOrder.address;
    [_addressView addSubview:addressLabel];
    
    // 指示标识
    UIImageView *accessoryImage = [[UIImageView alloc] init];
    accessoryImage.frame = CGRectMake(BVScreenW - 10 - 13, 20, 13, 20);
    accessoryImage.image = [UIImage imageNamed:@"qrdd_gray_go"];
    [_addressView addSubview:accessoryImage];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addressModify)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [_addressView addGestureRecognizer:tap];
}

#pragma mark -- UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.times.count == 0) {
        return 0;
    }
    return self.times.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    BVTime *time = self.times[section];
    
    if (time.duration_list.count == 0) {
        return 0 ;
    }
    
    return time.duration_list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 创建cell
    BVTimeCell *cell = [BVTimeCell cellWithTableView:tableView];
    
    // 传递模型
    BVTime *time = self.times[indexPath.section];
    cell.time = time.duration_list[indexPath.row];
    
    return cell;
}

#pragma mark -- UITableViewDelegate
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    BVTime *time = self.times[section];
    
    return time.current_date;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BVTime *time = self.times[indexPath.section];
    
    // 保存送货时间
    self.myTime = time;
    
    BVDurationTime *durationTime = time.duration_list[indexPath.row];
    
    self.getSendLabel.text = [NSString stringWithFormat:@"%@ - %@", durationTime.starttime, durationTime.endtime];
    
    // 移除蒙板
    [self.coverButton removeFromSuperview];
}

#pragma mark -- button点击事件
/**
 *  在线支付
 */
- (void)onlineSelectedButtonClick:(UIButton *)button {
    if (button.selected) {
        button.selected = NO;
        self.currentSelectedButton.selected = YES;
    } else {
        button.selected = YES;
        self.currentSelectedButton.selected = NO;
    }
}

/**
 *  货到付款
 */
- (void)currentSelectedButtonClick:(UIButton *)button {
    if (button.selected) {
        button.selected = NO;
        self.onlineSelectedButton.selected = YES;
    } else {
        button.selected = YES;
        self.onlineSelectedButton.selected = NO;
    }
}

#pragma 手势操作
/**
 *  切换地址
 */
- (void)addressModify {
    BVRecevicedAddressViewController *recevicedAddVC = [[BVRecevicedAddressViewController alloc] init];
    recevicedAddVC.delegate = self;
    ROOTNAVPUSH(recevicedAddVC, YES);
}

/**
 *  添加订单备注
 */
- (void)addRemark {
    BVAddOrderRemarksViewController *addOrderRemarkVC = [[BVAddOrderRemarksViewController alloc] init];
    addOrderRemarkVC.delegate = self;
    ROOTNAVPUSH(addOrderRemarkVC, YES);
}

/**
 *  选择配送时间
 */
- (void)sendTimeSelected {
    // 添加蒙板
    UIButton *coverButton = [[UIButton alloc] init];
    coverButton.frame = self.view.bounds;
    coverButton.backgroundColor =  [UIColor colorWithRed:111 / 255.0 green:111 / 255.0 blue:111 / 255.0 alpha:0.8];
    [coverButton addTarget:self action:@selector(coverButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    [window addSubview:coverButton];
    self.coverButton = coverButton;
    
    // 添加tableview
    [coverButton addSubview:self.tableView];
    
    // 刷新tableview
    [self.tableView reloadData];
}

- (void)coverButtonClick:(UIButton *)button {
    [button removeFromSuperview];
}

/**
 *  抵价券选择
 */
- (void)discountClick {
    
    if (self.currentSelectedButton.selected) {
        [MBProgressHUD showError:@"抵价券仅支持在线支付" toView:self.view];
    } else {
        BVDiscountViewController *discountVC = [[BVDiscountViewController alloc] init];
        discountVC.delegate = self;
        discountVC.goodsMoney = [self getGoodMoney];
        ROOTNAVPUSH(discountVC, YES);
    }
}

#pragma mark -- BVRecevicedAddressViewControllerDelegate
- (void)recevicedAddressDidFinish:(BVRecevicedAddressViewController *)recevicedAddress addrss:(BVReceviceAddress *)address {
    
    self.receviceAddress = address;
    
    for (id obj in self.addressView.subviews) {
        [obj removeFromSuperview];
    }
    
    // 地址标识
    UIImageView *addressImage = [[UIImageView alloc] init];
    addressImage.frame = CGRectMake(10, 20, 15, 20);
    addressImage.image = [UIImage imageNamed:@"qrdd_address"];
    [_addressView addSubview:addressImage];
    
    // 收获人姓名
    UILabel *receviceNameLabel = [[UILabel alloc] init];
    NSString *receviceName = address.contact;
    CGFloat addressW = [NSString sizeWithText:receviceName font:[UIFont systemFontOfSize:15]].width;
    receviceNameLabel.frame = CGRectMake(CGRectGetMaxX(addressImage.frame) + 10, 10, addressW, 20);
    receviceNameLabel.font = [UIFont systemFontOfSize:15];
    receviceNameLabel.text = receviceName;
    [_addressView addSubview:receviceNameLabel];
    
    // 收货人联系方式
    UILabel *mobileLabel = [[UILabel alloc] init];
    NSString *mobileStr = address.mobile;
    CGFloat mobileW = [NSString sizeWithText:mobileStr font:[UIFont systemFontOfSize:15]].width;
    mobileLabel.frame = CGRectMake(CGRectGetMaxX(receviceNameLabel.frame) + 10, receviceNameLabel.y, mobileW, 20);
    mobileLabel.font = [UIFont systemFontOfSize:15];
    mobileLabel.text = mobileStr;
    [_addressView addSubview:mobileLabel];
    
    // 收货地址
    UILabel *addressLabel = [[UILabel alloc] init];
    addressLabel.frame = CGRectMake(receviceNameLabel.x, CGRectGetMaxY(receviceNameLabel.frame) + 5, BVScreenW - receviceNameLabel.x - 23, 20);
    addressLabel.font = [UIFont systemFontOfSize:14];
    addressLabel.text = address.receive_address;
    [_addressView addSubview:addressLabel];
    
    // 指示标识
    UIImageView *accessoryImage = [[UIImageView alloc] init];
    accessoryImage.frame = CGRectMake(BVScreenW - 10 - 13, 20, 13, 20);
    accessoryImage.image = [UIImage imageNamed:@"qrdd_gray_go"];
    [_addressView addSubview:accessoryImage];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addressModify)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [_addressView addGestureRecognizer:tap];
}

#pragma mark -- BVAddOrderRemarksViewControllerDelegated
- (void)addOrderRemarks:(BVAddOrderRemarksViewController *)addOrderRemarks content:(NSString *)content {
    self.remindLabel.text = content;
}

#pragma mark -- BVDiscountViewControllerDelegate
- (void)discountViewController:(BVDiscountViewController *)discount myDiscount:(BVMyDiscount *)myDiscount {
    
    CGFloat goodsMoney = [self getGoodMoney];
    CGFloat distributeMoney = [self getDistributeMoeny:goodsMoney];
    CGFloat totolMoney = goodsMoney + distributeMoney;
    
    if (myDiscount != nil) {
        self.disCountView = [[UIView alloc] init];
        self.disCountView.frame = CGRectMake(0, CGRectGetMaxY(self.shopInfo.frame), BVScreenW, 40);
        self.disCountView.backgroundColor =  BVColor(233, 234, 235);
        [self.scrollView addSubview:self.disCountView];
        
        // 分割线
        UIView *separatorLine = [[UIView alloc] init];
        separatorLine.frame = CGRectMake(10, 0, BVScreenW - 2 * 10, 0.8);
        separatorLine.backgroundColor = [UIColor blackColor];
        separatorLine.alpha = 0.15;
        [self.disCountView addSubview:separatorLine];
        
        // 抵价券
        UILabel *discountLabel = [[UILabel alloc] init];
        discountLabel.frame = CGRectMake(10, 0.8, 80, 39.2);
        discountLabel.text = @"抵价券";
        discountLabel.textColor = BVBaseOrangeColor;
        discountLabel.font = [UIFont systemFontOfSize:15];
        [self.disCountView addSubview:discountLabel];
        
        // 抵价券金额
        UILabel *discountPriceLabel = [[UILabel alloc] init];
        discountPriceLabel.frame = CGRectMake(CGRectGetMaxX(discountLabel.frame) + 10, discountLabel.y, BVScreenW - CGRectGetMaxX(discountLabel.frame) - 2 * 10, discountLabel.height);
        discountPriceLabel.text = @"-¥";
        discountPriceLabel.textAlignment = NSTextAlignmentRight;
        discountPriceLabel.textColor = BVBaseOrangeColor;
        discountPriceLabel.font = [UIFont systemFontOfSize:13];
        [self.disCountView addSubview:discountPriceLabel];
        self.discountPriceLabel = discountPriceLabel;
        
        self.myDiscount = myDiscount;
        self.getDiscountLabel.text = [NSString stringWithFormat:@"使用%@元抵金券", myDiscount.couponMoney];
        // 优惠抵价券金额
        self.discountPriceLabel.text = [NSString stringWithFormat:@"-¥%@", myDiscount.couponMoney];
        
        totolMoney = totolMoney - myDiscount.couponMoney.floatValue;
     
        CGFloat maxHeight = CGRectGetMaxY(self.disCountView.frame) + 15;
        if (maxHeight > BVScreenH - 40 - 64) {
            self.scrollView.contentSize = CGSizeMake(0, maxHeight + 60);
        }
    } else {
        
        //self.disCountView.hidden = YES;
        [self.disCountView removeFromSuperview];
        self.disCountView = nil;
        
        self.getDiscountLabel.text = @"未选择抵价券";
        
        // scrollview的contentSize
        CGFloat maxHeight = CGRectGetMaxY(self.shopInfo.frame) + 15;
        if (maxHeight > BVScreenH - 40 - 64) {
            self.scrollView.contentSize = CGSizeMake(0, maxHeight + 60);
        }
    }
    
    // 重新计算总价格
    self.priceLabel.text = [NSString stringWithFormat:@"总计:%.2f", self.allPrice - [myDiscount.couponMoney floatValue]];
}

#pragma mark -- 设置导航栏
- (void)setupNav {
    
    self.navigationController.navigationBar.barTintColor = BVBaseOrangeColor;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.title = @"确认订单";
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(backClick)];
}

#pragma mark -- 返回
- (void)backClick {
    ROOTNAVPOP
}
- (CGFloat)getDistributeMoeny:(CGFloat)currentMoney{
    
    return 0;
    
    if(currentMoney <= 68.00) return 6.00;
    if(currentMoney <= 158) return 4.00;
    if(currentMoney <= 218) return 2.00;
    return 0;
}
- (CGFloat)getGoodMoney{
    BVNextOrder *nextOrder = self.nextOrder[0];
    
    CGFloat allPrice = 0.0;
    for (NSInteger i = 0; i < nextOrder.order_assort.count; i++) {
        BVNextOrderShopDetail *shopDetail = nextOrder.order_assort[i];
        
        allPrice += [shopDetail.sum_money floatValue];
    }
    return allPrice;
}
@end
